//
//  WelcomeViewController.swift
//  glzbowei
//
//  Created by 高伦展 on 2017/12/29.
//  Copyright © 2017年 glz. All rights reserved.
//

import UIKit
import SDWebImage

class WelcomeViewController: UIViewController {

    //设置界面
    override func loadView() {
        //直接使用背景图片作为根视图
        view = backImgView
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
         
        iconView.sd_setImage(with: UserAccountViewModel.sharedUserAccount.avatarUrl, placeholderImage: UIImage(named: "avatar_default_big"))
    }
    
    //
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        /**
         使用自动布局开发，有一个原则：
         -所有‘使用约束’设置位置的控件，不要再设置‘frame’
         
         * 原因：自动布局系统会根据设置的约束，自动计算控件的frame
         * 在 layoutSubviews 函数中设置 frame
         * 如果程序员主动修改 frame，会引起 自动布局系统计算错误
         
         -工作原理：当有一个运行循环启动，自动布局系统，会‘收集’所有的约束变化
         -在运行循环结束前，调用 layoutSubviews 函数 ‘统一’ 设置frame
         -如果希望某些约束提前更新！使用 ‘layoutIfNeeded’ 函数让自动布局系统，提前更新当前收集到的约束变化
         */
        
        iconView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom).offset(-view.bounds.height + 200)
        }
        
        welcomeLabel.alpha = 0
        UIView.animate(withDuration: 1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: [], animations: {
            
            //修改所有 ‘可动画’ 属性 - 自动布局的动画
            self.view.layoutIfNeeded()
        }) { (_) in
            UIView.animate(withDuration: 0.8, animations: {
                self.welcomeLabel.alpha = 1
            }, completion: { (_) in
                 
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBSwitchRootViewControllerNotification), object: nil)
            })
        }
    }

    //背景图片
    private lazy var backImgView :UIImageView = UIImageView(imgName: "ad_background")
    //头像
    private lazy var iconView:UIImageView = {
        let iv = UIImageView(imgName: "avatar_default_big")
        
        iv.layer.cornerRadius = 45
        iv.layer.masksToBounds = true
        
        return iv
    }()
    //欢迎标签
    private lazy var welcomeLabel:UILabel = UILabel(title: "欢迎回来", fontSize: 18.0)
}

// MARK: - 设置界面
extension WelcomeViewController{
    
    private func setupUI(){
        view.addSubview(iconView)
        view.addSubview(welcomeLabel)
        
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.bottom.equalTo(view.snp.bottom).offset(-200)
            make.width.equalTo(90)
            make.height.equalTo(90)
        }
        
        welcomeLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(iconView.snp.centerX)
            make.top.equalTo(iconView.snp.bottom).offset(16)
        }
    }
}
